package com.example.other.netty.test;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;

import java.util.concurrent.*;

public class NettyClient {
    public static void main(String[] args) {
        NioEventLoopGroup workerGroup = new NioEventLoopGroup();

        //指定线程模型、IO模型、连接读写处理逻辑
        Bootstrap bootstrap = new Bootstrap();
        //启动  bootstrap.group()返回的是线程模型
        bootstrap.group(workerGroup)
                .channel(NioSocketChannel.class)
                .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 5000)
                .handler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    protected void initChannel(SocketChannel socketChannel) throws Exception {
                        socketChannel.pipeline().addLast(new FirstClientHandler());
                    }
                });
        //注ce
        connect(bootstrap, "127.0.0.1", 8081, MAX_TRY);

    }

    private static final int MAX_TRY = 5;

    public static void connect(Bootstrap bootstrap, String ip, int port, int tryRelease){
        bootstrap.connect(ip,port).addListener(future -> {
            if(future.isSuccess()){
                System.out.println("连接成功。。。");
            } else if(tryRelease == 0){
                System.err.println("已重试5次，连接失败。。。");
            }else{
                int order = (MAX_TRY - tryRelease) +1;
                int delayTime = 1 << order;
                System.err.println("连接失败。。。" + "第" + order +"次重试");
                bootstrap.config().group().schedule(()->{
                    connect(bootstrap, ip, port, tryRelease-1);
                }, delayTime, TimeUnit.SECONDS);
            }
        });
    }
}
